package com.bw.common.utils

import android.util.Log
import java.io.File
import java.io.FileWriter
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

object LogUtil {
    // 日志全局开关
    var isDebug = true
    // 日志文件写入开关
    var isWriteToFile = false
    // 日志文件路径（可自定义）
    var logFilePath: String? = null
    // 默认TAG
    private const val DEFAULT_TAG = "SmartParkLog"
    // 单条日志最大长度（Logcat限制）
    private const val MAX_LOG_LENGTH = 3500

    fun v(tag: String = DEFAULT_TAG, msg: String) = log(Log.VERBOSE, tag, msg)
    fun d(tag: String = DEFAULT_TAG, msg: String) = log(Log.DEBUG, tag, msg)
    fun i(tag: String = DEFAULT_TAG, msg: String) = log(Log.INFO, tag, msg)
    fun w(tag: String = DEFAULT_TAG, msg: String) = log(Log.WARN, tag, msg)
    fun e(tag: String = DEFAULT_TAG, msg: String, throwable: Throwable? = null) = log(Log.ERROR, tag, msg, throwable)

    private fun log(priority: Int, tag: String, msg: String, throwable: Throwable? = null) {
        if (!isDebug && priority != Log.ERROR) return
        val fullMsg = if (throwable != null) msg + "\n" + Log.getStackTraceString(throwable) else msg
        // 长日志分段打印
        if (fullMsg.length > MAX_LOG_LENGTH) {
            var start = 0
            val length = fullMsg.length
            while (start < length) {
                val end = (start + MAX_LOG_LENGTH).coerceAtMost(length)
                printLog(priority, tag, fullMsg.substring(start, end))
                start = end
            }
        } else {
            printLog(priority, tag, fullMsg)
        }
        if (isWriteToFile) {
            writeLogToFile(priority, tag, fullMsg)
        }
    }

    private fun printLog(priority: Int, tag: String, msg: String) {
        when (priority) {
            Log.VERBOSE -> Log.v(tag, msg)
            Log.DEBUG -> Log.d(tag, msg)
            Log.INFO -> Log.i(tag, msg)
            Log.WARN -> Log.w(tag, msg)
            Log.ERROR -> Log.e(tag, msg)
            else -> Log.d(tag, msg)
        }
    }

    private fun writeLogToFile(priority: Int, tag: String, msg: String) {
        val path = logFilePath ?: return
        val logFile = File(path)
        val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault()).format(Date())
        val level = when (priority) {
            Log.VERBOSE -> "V"
            Log.DEBUG -> "D"
            Log.INFO -> "I"
            Log.WARN -> "W"
            Log.ERROR -> "E"
            else -> "D"
        }
        val logMsg = "$time [$level]/$tag: $msg\n"
        try {
            logFile.parentFile?.mkdirs()
            FileWriter(logFile, true).use { it.write(logMsg) }
        } catch (e: IOException) {
            Log.e(DEFAULT_TAG, "写日志到文件失败: ${e.message}")
        }
    }

    // 支持格式化输出
    fun df(tag: String = DEFAULT_TAG, format: String, vararg args: Any?) {
        d(tag, String.format(format, *args))
    }

    // 便捷方法：打印异常
    fun printStackTrace(tag: String = DEFAULT_TAG, throwable: Throwable) {
        e(tag, Log.getStackTraceString(throwable))
    }
} 